import {
  Button,
  Cell,
  CellGroup,
  DatePicker,
  Input,
  InputNumber,
  Picker,
  Radio,
} from "@nutui/nutui-react-taro";
import AddressRow from "@/pages/address/components/address-row";
import { AddressDto } from "@/apis/__generated/model/dto";
import { useImmer } from "use-immer";
import Taro from "@tarojs/taro";
import { TaskOrderInput } from "@/apis/__generated/model/static";
import localIcon from "@/assets/icons/location.png";
import editorIcon from "@/assets/icons/edit.png";
import weightIcon from "@/assets/icons/weight.png";
import boxIcon from "@/assets/icons/box.png";
import timeIcon from "@/assets/icons/time.png";
import mountedIcon from "@/assets/icons/mounted.png";
import { Image, Textarea, View } from "@tarojs/components";
import { ArrowRight } from "@nutui/icons-react-taro";
import dayjs from "dayjs";
import { Dictionaries } from "@/apis/__generated/model/enums/DictConstants";
import { dictToOptions, switchPage } from "@/utils/common";
import type {
  GoodsType,
  PayType,
  TaskType,
} from "@/apis/__generated/model/enums";
import RegisterPopup from "@/components/register-popup";
import { useAppDispatch } from "@/hook";
import { getUserInfo } from "@/features/user/userSlice";
import { api } from "@/utils/api-instance";
import "./index.scss";

export const handleWeChatPay = (id: string) => {
  return new Promise<boolean>((resolve, reject) => {
    api.taskOrderForFrontController
      .prepayWechat({ id })
      .then((res) => {
        Taro.requestPayment({
          nonceStr: res.nonceStr,
          package: res.packageValue,
          paySign: res.paySign,
          timeStamp: res.timeStamp,
          signType: res.signType as "RSA",
          success: () => {
            Taro.showToast({
              title: "支付成功",
              icon: "success",
            });
            resolve(true);
          },
          fail: (error) => {
            console.log(error);
            reject(error);
            Taro.hideLoading();
          },
        });
      })
      .catch((err) => {
        reject(err);
      });
  });
};
export default function Index() {
  const dispatch = useAppDispatch();

  const [order, setOrder] = useImmer<Partial<TaskOrderInput>>({
    endTime: "",
    startTime: "",
    status: "TO_BE_PAID",
    weight: 0,
    payType: "WE_CHAT_PAY",
  });
  const [timeVisible, setTimeVisible] = useImmer<boolean>(false);
  const [taskVisible, setTaskVisible] = useImmer<boolean>(false);
  const [goodsVisible, setGoodsVisible] = useImmer<boolean>(false);
  Taro.eventCenter.on(
    "sourceAddress",
    (value: AddressDto["AddressRepository/COMPLEX_FETCHER_FOR_FRONT"]) => {
      setOrder((draft) => {
        draft.sourceAddress = value;
      });
    },
  );
  Taro.eventCenter.on(
    "targetAddress",
    (value: AddressDto["AddressRepository/COMPLEX_FETCHER_FOR_FRONT"]) => {
      setOrder((draft) => {
        draft.targetAddress = value;
      });
    },
  );
  Taro.useLoad(() => {
    dispatch(getUserInfo());
  });
  const handleSubmit = async () => {
    Taro.showLoading();
    const startTime =
      dayjs().format("YYYY-MM-DD") + " " + order.startTime + ":00";
    if (!order.type) {
      return Taro.showToast({
        title: "请选择跑腿类型",
        icon: "none",
      });
    }
    if (!order.sourceAddress) {
      return Taro.showToast({
        title: "请选择开始地址",
        icon: "none",
      });
    }
    if (!order.targetAddress) {
      return Taro.showToast({
        title: "请选择目标地址",
        icon: "none",
      });
    }
    if (!order.weight) {
      return Taro.showToast({
        title: "请输入重量",
        icon: "none",
      });
    }
    if (!order.goodsType) {
      return Taro.showToast({
        title: "请选择商品类型",
        icon: "none",
      });
    }

    const res = await api.taskOrderForFrontController.create({
      body: {
        ...(order as TaskOrderInput),
        startTime: startTime,
        endTime: startTime,
      },
    });
    if (order.payType == "WE_CHAT_PAY") {
      await handleWeChatPay(res);
    } else {
      await api.taskOrderForFrontController.walletPay({ id: res });
    }
    Taro.hideLoading();
    Taro.navigateTo({ url: "./order-list" });
  };
  //TODO 支付方式
  return (
    <div className="order-submit">
      <CellGroup>
        <Cell
          clickable
          align="center"
          onClick={() =>
            switchPage("../address/address-list?event=sourceAddress")
          }
          title={
            <div className="title">
              <Image className="icon" src={localIcon}></Image>
              {order.sourceAddress ? (
                <AddressRow address={order.sourceAddress}></AddressRow>
              ) : (
                <View className="input-wrapper placeholder">
                  请选择开始地址
                </View>
              )}
            </div>
          }
          extra={<ArrowRight />}
        ></Cell>
        <Cell
          clickable
          align="center"
          onClick={() =>
            switchPage("../address/address-list?event=targetAddress")
          }
          title={
            <div className="title">
              <Image className="icon" src={localIcon}></Image>
              {order.targetAddress ? (
                <AddressRow address={order.targetAddress}></AddressRow>
              ) : (
                <View className="input-wrapper placeholder">
                  请选择目标地址
                </View>
              )}
            </div>
          }
          extra={<ArrowRight />}
        ></Cell>

        <Cell
          clickable
          align="center"
          onClick={() => setTaskVisible(true)}
          title={
            <div className="title">
              <Image className="icon" src={mountedIcon}></Image>
              <Input
                placeholder="请选择跑腿类型"
                value={
                  order.type ? Dictionaries.TaskType[order.type].keyName : ""
                }
                readOnly
              ></Input>
            </div>
          }
        ></Cell>
        <Cell
          clickable
          align="center"
          onClick={() => setGoodsVisible(true)}
          title={
            <div className="title">
              <Image className="icon" src={boxIcon}></Image>
              <Input
                placeholder="请选择物品类型"
                value={
                  order.goodsType
                    ? Dictionaries.GoodsType[order.goodsType].keyName
                    : ""
                }
                readOnly
              ></Input>
            </div>
          }
        ></Cell>
        <Cell
          clickable
          align="center"
          onClick={() => setTimeVisible(true)}
          title={
            <div className="title">
              <Image className="icon" src={timeIcon}></Image>
              <Input
                placeholder="请选择预计送达时间"
                value={order.startTime}
                readOnly
              ></Input>
            </div>
          }
        ></Cell>
        <Cell
          clickable
          align="center"
          title={
            <div className="title">
              <Image className="icon" src={weightIcon}></Image>
              <div className="input-wrapper">
                <InputNumber
                  min={0}
                  step={0.1}
                  onChange={(value) => {
                    setOrder((draft) => {
                      draft.weight = parseFloat(value + "");
                    });
                  }}
                ></InputNumber>
              </div>
              <div className="unit">KG</div>
            </div>
          }
        ></Cell>
        <Cell
          clickable
          align="center"
          title={
            <div className="title">
              <Image className="icon" src={editorIcon}></Image>
              <div className="input-wrapper">
                <Textarea
                  value={order.remark}
                  style={{ height: "100rpx" }}
                  placeholder="请输入备注"
                  onInput={(e) => {
                    setOrder((draft) => {
                      draft.remark = e.detail.value;
                    });
                  }}
                ></Textarea>
              </div>
            </div>
          }
        ></Cell>
        <Cell
          clickable
          align="center"
          title={
            <div className="title">
              <Image className="icon" src={editorIcon}></Image>
              <div className="input-wrapper">
                <Radio.Group
                  value={order.payType}
                  onChange={(e) => {
                    setOrder((draft) => {
                      draft.payType = e as PayType;
                    });
                  }}
                >
                  {dictToOptions(Dictionaries.PayType).map((row) => (
                    <Radio value={row.value} key={row.value}>
                      {row.text}
                    </Radio>
                  ))}
                </Radio.Group>
              </div>
            </div>
          }
        ></Cell>
      </CellGroup>
      <div className="submit-bar-wrapper">
        <div className="submit-bar">
          <div className="price">
            ￥{order.weight ? (order.weight * 2).toFixed(1) : 0}
          </div>
          <Button type="primary" onClick={() => handleSubmit()}>
            提交订单
          </Button>
        </div>
      </div>
      <Picker
        title="请选择跑腿类型"
        visible={taskVisible}
        options={dictToOptions(Dictionaries.TaskType)}
        onConfirm={(_list, values) => {
          setOrder((draft) => {
            draft.type = values[0] as TaskType;
          });
        }}
        onClose={() => setTaskVisible(false)}
      />
      <Picker
        title="请选择物品类型"
        visible={goodsVisible}
        options={dictToOptions(Dictionaries.GoodsType)}
        onConfirm={(_list, values) => {
          setOrder((draft) => {
            draft.goodsType = values[0] as GoodsType;
          });
        }}
        onClose={() => setGoodsVisible(false)}
      />
      <DatePicker
        title="时间选择"
        type="hour-minutes"
        visible={timeVisible}
        startDate={new Date()}
        onClose={() => setTimeVisible(false)}
        onConfirm={(_options, values) => {
          setOrder((draft) => {
            draft.startTime = values.join(":");
          });
        }}
      />
      <RegisterPopup></RegisterPopup>
    </div>
  );
}
